package com.bcntouch.touch2act.NFC;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import android.content.Intent;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Parcelable;

public class NFCUtils {

	public static String getTagUidFromIntent(Intent intent) {
		String uid = null;
		if ( intent.hasExtra( NfcAdapter.EXTRA_ID ) ) {
		    byte[] extraBytes = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
		    
		    if ( ( extraBytes != null ) && ( extraBytes.length > 1 ) ) {
		    	uid = getTagUidFromByteArray(extraBytes);
		    }
		}
		
		return uid;
	}
	
	public static String getTagUidFromByteArray(byte[] bytes) {
		String uid = new String();
		
		for ( byte b : bytes )
			uid += String.format(Locale.US, "%02x", b );
		
		return uid;
	}
	
	public static NdefMessage[] getNdefMessages(Intent intent) {
		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		if (rawMsgs == null)
			return null;
		
    	NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
        for (int i = 0; i < rawMsgs.length; i++) {
            msgs[i] = (NdefMessage) rawMsgs[i];
        }
        
        return msgs;
	}
	
	public static List<Uri> getUris(NdefMessage[] messages) {
		if (messages == null)
			return null;
		
		LinkedList<Uri> uris = new LinkedList<Uri>();
		for (NdefMessage message : messages) {
			NdefRecord[] records = message.getRecords();
			for (NdefRecord record : records) {
				if ( UriNdefRecord.isUri( record ) ) {
	                uris.add(UriNdefRecord.parse(record).getUri());
	            }
			}
		}
		
		if (uris.isEmpty())
			uris = null;
		
		return uris;
	}
	
	public static List<Uri> getUris(Intent intent) {
		NdefMessage[] messages = getNdefMessages(intent);
		return getUris(messages);
	}
}
